<?php
// +----------------------------------------------------------------------
// | 后台用户管理
// +----------------------------------------------------------------------
namespace app\common\model;
use think\Model;
use think\Validate;
use base\other\Strings;

class ShopYyOrder extends Model
{
	// ----------------
	// ---模型事件---
	//----------------
	protected static function init()
	{
    	//插入前验证
    	self::event('before_insert', function ($param) {
	    	$validate = new Validate;
			$validate->rule([
				'uid|会员'=>'require|integer',
				'shop_id|店铺'=>'require|integer',
				'staff_id|员工'=>'require|integer',
				'proj_id|项目'=>'require|integer',
				'date|日期'=>'require',
				'times|时间段'=>'require',
				'duration|时长'=>'require',
			]);
	        if(!$validate->check($param)){
	        	throw new \think\Exception($validate->getError());
	        }
        });
        //新增后
        self::event('after_insert', function ($data) {
			model('msg')->send(0,$data['uid'],'预约处理通知',"预约成功，请及时到店服务！");
        });
    	//更新后-发送通知
    	self::event('after_update', function ($data) {
    		$title  = '预约处理通知';
        	switch($data->status ?? 0){
			    case 1: //完成
					$msg = "您的预约单已完成！";
					model('msg')->send(0,$data['uid'],$title,$msg);
			        break;  
			    case 2: //取消
					$msg = "您的预约单已取消！";
					model('msg')->send(0,$data['uid'],$title,$msg);
			        break;        
			    case -1://已过期
			   		$msg = "您的预约单已过期！";
					model('msg')->send(0,$data['uid'],$title,$msg);
			      	break;            
			}
        });
    }
    
	// ---------------------
	// ---字段自动完成---
	//---------------------
	protected $insert = ['no'];
	protected function setNoAttr() {
		return Strings::createOrderNo('yy');
    }
    protected function getStatusAttr($value,$data) {
    	$date = date('Y-m-d', strtotime($data['date']));
    	$times =explode("-",$data['times']);
    	$time = strtotime(date("Y-m-d H:i"));
    	$end = strtotime(date("Y-m-d H:i", strtotime("+2 hour", strtotime($date .' '.$times[0]))));
    	if( $value == 0 && $time > $end ){
    		return -1;
    	}
    	$end =  strtotime($date.' '.$times[0]);
    	if( $value == 0 && $time > strtotime($date.' '.$times[0]) &&  $time < $end ){
    		return 3;
    	}
		return $value;
    }
    
	
	//店铺，一对一关联
	public function shop(){
        return $this->hasOne('shop','id','shop_id');
    }
	
	//店员，一对一关联
	public function staff(){
        return $this->hasOne('ShopStaff','id','staff_id');
    }
	
	//项目，一对一关联
	public function project(){
        return $this->hasOne('UserYgProj','id','proj_id');
    }
    
   	//关联评价内容，一对一关联
	public function evaluate(){
        return $this->hasOne('ShopStaffEvaluate','order_id','id');
	}
    
    //获取模型
	public function getModel(){
		//基础参数
		$uid = request()->userInfo['id'];
		$shopId =  request()->shopId;
		//基础模型
        $model = self::with([
			'staff'=> function($query) { 
				$query->field('id,name,img,work_type'); 
				$query->withAvg(['evaluate'=>function($query){
				    $query->where('is_del',0)->field('staff_id,service_score');
				    return 'star';
				}],'service_score');
			},
			'project'=> function($query) { 
				$query->with(['goods','specs']);
			},
			'shop'=> function($query) { 
				$query->field('id,name,region,address_detail,latitude,longitude');
	        	$query->field('img,banners,phone,remark');
	        	$query->field("concat(province,city,address_detail) as addr");
			}
		]);
		$model = $model->withCount('evaluate');
    	$model = $model->where('uid',$uid);	
    	//$model = $model->where('shop_id',$shopId);	
    	$model = $model->field('*');	
    	$model = $model->order('add_time','desc');	
    	$model = $model->page(input('pageIndex') ?: 1,input('pageSize') ?: 20);
    	//返回模型
    	return $model;
    }
    
	/**
     * 获取用户预约
     * @param type $uid
     * @return type
     */
	public function getUserYy($status='all')
    {
    	$model = self::getModel();
    	if($status !='' && $status!='all' && $status != '-1'){
    		$model->where('status',$status);	
    	}
		return $model->select();
    }
    
    /**
     * 取消
     * @param type $uid
     * @return type
     */
	public function cancel($id)
    {
    	if( !$order = self::get($id) ){
    		throw new \think\Exception('订单不存在!');
    	}    	
    	if($order->status!=0){
    		throw new \think\Exception('当前状态不能取消!');
    	}

    	$proj  = $order->project;
    	$proj->use_num = $proj->use_num - 1;
    	$proj->save();
    	
		$order->status = 2;
		$order->save();
		
    }
    
    
    /**
     * 完成
     * @param type $uid
     * @return type
     */
	public function complete($id)
    {
    	if(!$order = self::get($id)){
    		throw new \think\Exception('订单不存在!');
    	}
    	if($order->status==1){
    		return true;
    	}
    	
    	$proj  = $order->project;
    	$proj->use_num = $proj->use_num + 1;
    	$proj->save();
    	
		$order->status = 1;
		$order->save();
		
		//添加使用记录
		model('UserYgProjUseLog')->save([
			'link_id'=>$order->no,
			'proj_id'=>$proj->id,
			'type'=>1
		]);
    }
    
    /**
     * 自动完成
     * @param type $uid
     * @return type
     */
	public function autoComplete()
    {
    	
    }
    
}
